package com.uenpay.im.ui.old.activity.wallet;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.qiyunxin.android.http.utils.Utils;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.bankcard.BankEntity;
import com.uenpay.im.ui.old.activity.bankcard.ChooseBankCardActivity;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.invokeitems.HttpPostRequest;
import com.uenpay.im.pay.PayHandle;
import com.uenpay.im.weight.PayPwdDialog;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.MessageFormat;

/**
 * @author SL
 * @created 2016-1-14 19:29:52
 * @copyRight http://www.qiyunxin.com
 * @function 提现
 */
public class CashActivity extends BaseActivity {

    private EditText amout_et;
    private Button next_btn;
    private String balance;
    private TextView error_tv, choose_tv;
    private BankEntity bankEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_cash_layout;
    }

    @Override
    public void initView(View view) {
        balance = getIntent().getStringExtra("balance");
        initView();
        initListener();
        Utils.showSoftKeyboard(amout_et);
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.red_cash));
        next_btn = (Button) findViewById(R.id.next_btn);
        amout_et = (EditText) findViewById(R.id.amout_et);
        error_tv = (TextView) findViewById(R.id.error_tv);
        choose_tv = (TextView) findViewById(R.id.choose_tv);
        amout_et.setHint(MessageFormat.format(
                getResources().getString(R.string.account_balance), balance));
    }

    protected void initListener() {
        findViewById(R.id.choose_layout).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.hideSoftKeyboard(amout_et);
                Intent intent = new Intent(CashActivity.this, ChooseBankCardActivity.class);
                intent.putExtra("slectedEntity", bankEntity);
                startActivityForResult(intent, 100);
            }
        });
        findViewById(R.id.back_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Utils.hideSoftKeyboard(amout_et);
                        finish();
                    }
                });
        amout_et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                setTotalMoney();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
        next_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String amount = amout_et.getText().toString();
                // TODO 提示未绑定银行卡
                if (TextUtils.isEmpty(amount)) {
                    IMApplication.showToast(R.string.input_cash_amount);
                } else if (bankEntity == null) {
                    IMApplication.showToast(R.string.choose_bank_crad);
                } else {
                    double t = Double.valueOf(amount);
                    Utils.hideSoftKeyboard(amout_et);
                    showPayPwdDialog(t * 100);
                }
            }
        });
    }

    private void showPayPwdDialog(final double amount) {
        PayPwdDialog.showBottomRedDialog(CashActivity.this, new PayPwdDialog.IPayPwdInputFinishListener() {
            @Override
            public void onPayPwdInputFinish(String payPwd) {
                getPayToken(payPwd, amount);
            }
        });
    }

    private void getPayToken(String payPwd, final double amount) {
        PayHandle.getPayToken(payPwd, new PayHandle.IGetPayTokenResult() {
            @Override
            public void onResult(int status, String payToken) {
                if (status == 0) {
                    cash(payToken, amount);
                }
            }
        });
    }

    private void cash(String pay_token, double amount) {
        String url = APIConfiguration.getPayUrl() + "useraccountwithdraw/" + IMApplication.getInstance().getUcrOpendId() + "/apply";
        JSONObject json = new JSONObject();
        try {
            json.put("pay_token", pay_token);
            json.put("amount", amount);
            json.put("bankcard_id", bankEntity.id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpPostRequest.onRequest(url, json.toString(), HttpPostRequest.REQUESTMETHOD_POST, new HttpPostRequest.IRequest() {
            @Override
            public void onResult(int responseCode, String response) {
                if (responseCode == 200) {
                    IMApplication.showToast(R.string.transaction_success);
                    setResult(RESULT_OK);
                    finish();
                } else {
                    if (!TextUtils.isEmpty(response)) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            IMApplication.showToast(jsonObject.optString("err_msg"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

    }

    private void setTotalMoney() {
        String money = amout_et.getText().toString();
        double balances = Double.valueOf(balance);
        try {
            double sigleMoney = Double.valueOf(money);
            if (sigleMoney > balances) {
                error_tv.setVisibility(View.VISIBLE);
                next_btn.setEnabled(false);
            } else {
                error_tv.setVisibility(View.INVISIBLE);
                next_btn.setEnabled(true);
            }
        } catch (Exception e) {
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == 100) {
            if (data != null && data.hasExtra("slectedEntity")) {
                bankEntity = (BankEntity) data.getSerializableExtra("slectedEntity");
                choose_tv.setText(bankEntity.bank_name + "（" + bankEntity.card_no.substring(bankEntity.card_no.length() - 5, bankEntity.card_no.length()) + "）");
            }
        }
        super.onActivityResult(requestCode, resultCode, data);

    }
}
